#include "FileIO.h"
#include <memory>

CFileIO::CFileIO()
{
	m_bFlagCreate = false;
}

CFileIO::~CFileIO()
{
	if(m_bFlagCreate)
		Destroy();
}

bool CFileIO::Create(const char* ptrFilename, OPEN_TYPE open)
{
	if(m_bFlagCreate || !ptrFilename)
		return false;

	if(open == WRITE)
		m_ptrFile = fopen(ptrFilename, "w");
	else
		m_ptrFile = fopen(ptrFilename, "r+");

	if(!m_ptrFile)
		return false;

	m_bFlagCreate = true;

	return true;
}

bool CFileIO::Destroy()
{
	if(!m_bFlagCreate)
		return false;

	fclose(m_ptrFile);

	m_bFlagCreate = false;

	return true;
}

bool CFileIO::ReadLine(char* ptrBuffer, int nMaxBufferSize)
{
	if(!m_bFlagCreate || !ptrBuffer)
		return false;

	int		nCnt	= 0;
	char	ch		= 0;

	memset(ptrBuffer, 0, nMaxBufferSize);

	while(ch != '\n')
	{
		if(feof(m_ptrFile))	return false;

		ch = fgetc(m_ptrFile);

		ptrBuffer[nCnt] = ch;
		nCnt++;
	}

	return true;
}

bool CFileIO::WriteLine(const char* ptrBuffer)
{
	if(!m_bFlagCreate || !ptrBuffer)
		return false;

	fprintf(m_ptrFile, "%s\n", ptrBuffer);

	return true;
}

bool CFileIO::Write(const char* ptrBuffer)
{
	if(!m_bFlagCreate || !ptrBuffer)
		return false;

	fprintf(m_ptrFile, "%s", ptrBuffer);

	return true;
}


